package com.finger.forest;

import android.content.Context;
import android.nfc.Tag;
import android.os.Bundle;
import android.os.Handler;
import android.util.ArrayMap;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.finger.forest.base.BaseActivity;
import com.finger.forest.base.BaseView;
import com.finger.forest.base.CommonKey;
import com.finger.forest.base.ResponseTag;
import com.finger.forest.http.presenter.RegisterPresenter;
import com.finger.forest.model.LoginModel;
import com.finger.forest.model.NoticeItemModel;
import com.finger.forest.model.ResponseModel;
import com.finger.forest.model.WorkLogModel;
import com.finger.forest.utils.AndroidUtil;
import com.finger.forest.utils.ClickUtils;
import com.finger.forest.utils.DateUtil;
import com.finger.forest.utils.ToastUtils;
import com.finger.forest.utils.encode.PrefsUtil;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 工作日志
 */
public class WorkLogActivity extends BaseActivity<RegisterPresenter> implements BaseView {

    private static final String TAG = "WorkLogActivity";

    /**
     * 返回
     */
    @BindView(R.id.btn_back)
    ImageView backIv;

    /**
     * 日期
     */
    @BindView(R.id.tv_date)
    TextView dateTv;

    /**
     * 月份
     */
    @BindView(R.id.tv_month)
    TextView monthTv;

    /**
     * 日历布局
     */
    @BindView(R.id.layout_calendar)
    LinearLayout calendarLayout;

    /**
     * 提交
     */
    @BindView(R.id.tv_submit)
    TextView submitTv;

    /**
     * 工作日志内容
     */
    @BindView(R.id.et_content)
    EditText contentEt;

    /**
     * 工作日志内容
     */
    @BindView(R.id.tv_content)
    TextView contentTv;

    @BindView(R.id.scrollView)
    HorizontalScrollView scrollView;

    Handler handler = new Handler();

    private Calendar selectedDate;
    private Calendar startDate;
    private Calendar endDate;

    @Override
    protected int setView() {
        return R.layout.activity_work_log;
    }

    @Override
    protected void receiveData() {

    }

    @Override
    protected void initializeView() {

        selectedDate = Calendar.getInstance();
        startDate = Calendar.getInstance();
        endDate = Calendar.getInstance();
        //正确设置方式 原因：注意事项有说明
        startDate.set(2018, 0, 1);
        endDate.set(2040, 0, 1);

        //初始化日期
        dateTv.setText(DateUtil.dateToStr(DateUtil.DATE_FORMAT));

        //初始化月份
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH)+1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        monthTv.setTag(year);
        monthTv.setText(month + "月");

        //初始化日历
        List<Map<String,String>> calList = new ArrayList<>();
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.MONTH, month-1);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        while (cal.get(Calendar.MONTH) == (month-1)){
            Map<String,String> mapT = new HashMap<>();
            mapT.put("week", DateUtil.getDayName(cal.get(Calendar.DAY_OF_WEEK)));
            mapT.put("day", cal.get(Calendar.DAY_OF_MONTH)+"");
            calList.add(mapT);
            cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH)+1);
        }
        for (int i=0;i<calList.size();i++){
            Map<String,String> mapT = calList.get(i);
            LinearLayout ll = (LinearLayout)LayoutInflater.from(this).inflate(R.layout.item_calendar,null);
            TextView weekTv = ll.findViewById(R.id.tv_week);
            weekTv.setText(mapT.get("week").toString());
            TextView dayTv = ll.findViewById(R.id.tv_day);
            String dayStr = mapT.get("day").toString();
            dayTv.setText(dayStr);
            if (day == Integer.parseInt(mapT.get("day").toString())){
                weekTv.setTextColor(getResources().getColor(R.color.colorBlue));
                dayTv.setTextColor(getResources().getColor(R.color.colorBlue));
            }
            ll.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String year = monthTv.getTag().toString();
                    String monthTvStr = monthTv.getText().toString();
                    String month = getFormatDigit(monthTvStr.substring(0,monthTvStr.indexOf("月")));
                    String dateStr = year + "-" + month + "-" + getFormatDigit(dayStr);
                    Log.i(TAG,"点击查询日期："+dateStr);
                    queryWorkLog(dateStr);
                }
            });
            calendarLayout.addView(ll);
        }

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (scrollView != null){
                    //在该run方法中执行滚动操作
                    scrollView.scrollTo((day-1) * 80, 0);
                }
            }
        }, 2000); // 延迟2秒，再运行splashhandler的run()

        //初始化查询工作日志
        queryWorkLog(DateUtil.dateToStr(DateUtil.DATE_FORMAT));
    }

    @Override
    protected void loadDataFromServer() {

    }

    private void queryWorkLog(String dateStr){
        String userId = PrefsUtil.getString(this,CommonKey.USER_ID);
        Map<String, Object> maps = new HashMap<>();
        maps.put("userId",userId);
        maps.put("creatTime",dateStr);
        presenter.queryWorkLog(maps);
    }

    @OnClick({R.id.btn_back, R.id.tv_submit, R.id.tv_month })
    public void onClick(View v) {
        if (ClickUtils.isFastClick()) { //防止重复点击
            switch (v.getId()) {

                //返回
                case R.id.btn_back:
                    finish();
                    break;

                //提交
                case R.id.tv_submit:
                    String userId = PrefsUtil.getString(this,CommonKey.USER_ID);
                    Map<String, Object> maps = new HashMap<>();
                    maps.put("userid",userId);
                    maps.put("content",contentEt.getText().toString());
                    AndroidUtil.closeInputMethod(WorkLogActivity.this,contentEt);//关闭软键盘
                    presenter.submitWorkLog(maps);
                    break;

                //选择月份
                case R.id.tv_month:
                    //时间选择器
                    TimePickerView pvTimeStart = new TimePickerBuilder(WorkLogActivity.this, new OnTimeSelectListener() {
                        @Override
                        public void onTimeSelect(Date date, View v) {
                            Calendar calSelect = Calendar.getInstance();
                            calSelect.setTime(date);
                            int yearSelect = calSelect.get(Calendar.YEAR);
                            int monthSelect = calSelect.get(Calendar.MONTH)+1;
                            monthTv.setTag(yearSelect);
                            monthTv.setText(monthSelect+"月");
                        }
                    })
                            .setDate(selectedDate).setType(new boolean[]{true, true, false, false, false, false})
                            .setRangDate(startDate, endDate)//起始终止年月日设定
                            .build();
                    pvTimeStart.show();
                    break;

                default:
                    break;
            }
        }
    }

    @Override
    public void onSuccess(Object model, int tag, String msg) {

        switch (tag) {

            //初始化工作日志
            case ResponseTag.QUERY_WORK_LOG:
                List<WorkLogModel> workLogModelList = (List<WorkLogModel>) model;
                StringBuffer content = new StringBuffer();
                for (WorkLogModel workLog:workLogModelList){
                    content.append(workLog.getContent()+"\n");
                }
                contentTv.setText(content);
                break;

            //提交工作日志
            case ResponseTag.SUBMIT_WORK_LOG:
                contentEt.setText("");//置空
                queryWorkLog(DateUtil.dateToStr(DateUtil.DATE_FORMAT));
                ToastUtils.show(msg);
                break;
            default:
                break;
        }
    }

    @Override
    public void onError(int errcode, int tag, String message) {

    }


    private String getFormatDigit(String digit){
        if (digit.length() == 1){
            digit = "0"+digit;
        }
        return digit;
    }
}
